import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:animated_tree_view/animated_tree_view.dart' as treeview;
import 'package:yuellyfactory/util/MathUtil.dart';
import 'package:yuellyfactory/util/ToastUtil.dart';
import '../../components/NoScrollbarBehavior.dart';
import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ViewUtil.dart';
import '../../util/XNumberTextInputFormatter.dart';
import '../dto/PricePart.dart';

class ModelConfigVC extends StatefulWidget {
  final PricePart pricePart;
  final Function callback;
  const ModelConfigVC({super.key, required this.pricePart, required this.callback});

  @override
  State<ModelConfigVC> createState() => _ModelConfigVCState();
}

class _ModelConfigVCState extends State<ModelConfigVC> {

  List allDatas=[];
  treeview.TreeViewController? _controller;
  var sampleTree = treeview.TreeNode.root();

  PricePart selectPricePart=PricePart();
  Map hasSelect={};

  List<String> hasSelectIds=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initSelectData();
    getAllData();
  }

  @override
  Widget build(BuildContext context) {
    return ShadSheet(
      onClosing: () {
        debugPrint("关闭回调");
        widget.callback();
      },
      constraints:  BoxConstraints(minWidth: 1100, maxWidth: 1100,maxHeight: ViewUtil.matchHeight(context)-100,minHeight: ViewUtil.matchHeight(context)-100),
      title: Row(children: [
        const Text('型号配置'),
        const SizedBox(width: 50,),
        ViewUtil.doneIcon("保存配置", (){
          submit();
        })
      ],),
      child:
      Container(
        child:  ClipRRect(
          child: ShadResizablePanelGroup(
            children: [
              ShadResizablePanel(

                defaultSize: .5,
                minSize: .2,
                maxSize: .5,
                child: ShadResizablePanelGroup(
                  axis: Axis.horizontal,
                  children: [
                    ShadResizablePanel(
                    defaultSize: .6,
                      minSize: .4,
                      maxSize: .7,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(
                            child: Card( color: Colors.white,
                              child:
                              ScrollConfiguration(
                                behavior: NoScrollbarBehavior(),
                                child: SingleChildScrollView(
                                  child:
                                  Padding(
                                    padding: const EdgeInsets.all(5.0),
                                    child:
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        SizedBox(height: ViewUtil.screenWidth(10),),
                                        Text('已选配置',style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),
                                        SizedBox(height: ViewUtil.screenWidth(10),width: double.infinity,),
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: getAllSelectData(),
                                        )
                                      ],
                                    )


                                    ,
                                  ),),
                              ),

                            ),
                          ),
                        ],
                      ),

                    ),
                    ShadResizablePanel(
                      defaultSize: .4,
                      minSize: .3,
                      maxSize: .6,
                      child:
                      Card(
                          color: Colors.white,
                          child:Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              SizedBox(height: ViewUtil.screenHeight(10),),

                              // SizedBox(height: ViewUtil.screenHeight(10),),
                              Expanded(child:
                              treeview.TreeView.simple(
                                  showRootNode: false,
                                  focusToNewNode: false,
                                  expansionIndicatorBuilder: (context, node) {
                                    return treeview.ChevronIndicator.rightDown(
                                        tree: node,
                                        alignment: Alignment.centerRight,
                                        //color: Colors.grey[700],
                                        color:ColorUtil.colorBlue
                                    );
                                  },
                                  indentation: const treeview.Indentation(
                                      style: treeview.IndentStyle.roundJoint),
                                  onItemTap: (item) {
                                    print("Item tapped: ${item.key}");
                                    selectPricePart=item.data;
                                    setState(() {

                                    });
                                  },
                                  onTreeReady: (controller) {
                                    _controller = controller;
                                  },
                                  builder: (context, node) =>  Container(
                                    decoration: BoxDecoration(
                                      color: selectPricePart.id==node.key ? Colors.blue.withOpacity(0.1) : null,
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    child: ListTile(
                                      title: Text("${node.data.name}",style: TextStyle(fontSize: ViewUtil.fontSize(22)),),
                                      trailing:  !hasSelectIds.contains(node.data.id)&&node.data.type=='type'?

                                      const Icon(Icons.circle,color: Colors.red,size: 12,)
                                          :null,

                                    ),
                                  ),
                                  tree: sampleTree),)

                            ],
                          )

                      ),
                    ),
                  ],
                ),
              ),


              ShadResizablePanel(
                defaultSize: .5,
                child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                      child: Card( color: Colors.white,
                        child:
                        ScrollConfiguration(
                          behavior: NoScrollbarBehavior(),
                          child: SingleChildScrollView(
                            child:
                            Padding(
                              padding: const EdgeInsets.all(5.0),
                              child:
                              Column(
                                children: [
                                  SizedBox(height: ViewUtil.screenWidth(10),),
                                  Row(
                                    children: [
                                      SizedBox(width: ViewUtil.screenWidth(10),),
                                      Expanded(child: Text(selectPricePart.name,
                                        style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold)
                                        ,),),

                                    ],
                                  ),
                                  if(selectPricePart.type=='serial')
                                    allPartWidgets()
                                ],
                              )


                              ,
                            ),),
                        ),

                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),


      ),
    );
  }


  getAllSelectData(){
    List<Widget> widgets=[];
    for(PricePart type in allDatas){
      bool hasAddType=false;
      for(PricePart brand in type.materialList){
        for(PricePart serial in brand.materialList){

          for(PricePart part in serial.materialList){
            if(part.select){
              if(!hasAddType){
                widgets.add(Text(type.name,style: TextStyle(fontSize: ViewUtil.fontSize(28),fontWeight: FontWeight.bold),),);
              }
              hasAddType=true;
              widgets.add(Row(
                children: [
                  const SizedBox(width: 10,),
                  Text(part.name,style: TextStyle(fontSize: ViewUtil.fontSize(22)),),
                  Expanded(child: Container()),
                  Text('数量:${MathUtil.formatDouble(part.count, 2)}',style: TextStyle(fontSize: ViewUtil.fontSize(22)),),
                ],
              ));
            }

          }
        }

      }
    }

    return widgets;
  }

  void getAllData(){
    BaseRequest.postHttp("price/baselist",parameters: {}, canTip: false , context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        List allParts=[];
        for(var i=0;i<datas.length;i++){
          var item=datas[i];
          var part=PricePart.fromJson(item);
          allParts.add(part);
        }
        allDatas=allParts;
        initTreeDatas(allParts);
      }


    }, onError: (error){

    });
  }

  void updateRedPoint(){
    List<String> selectIds=[];
    for(PricePart type in allDatas){
      for(PricePart brand in type.materialList){
        for(PricePart serial in brand.materialList){
          for(PricePart part in serial.materialList){
             if(part.select){
               selectIds.add(type.id);
               selectIds.add(brand.id);
               selectIds.add(serial.id);
               selectIds.add(part.id);
             }
          }
        }

      }
    }
    hasSelectIds=selectIds;

    setState(() {

    });
  }


  Widget allPartWidgets(){

    List<Widget> views=[];
    for(PricePart part in selectPricePart.materialList){
      views.add(SizedBox(height: ViewUtil.screenHeight(10),));
      views.add(Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          FlutterSwitch(value: part.select,
              width: 40.0,
              height: 25.0,
              onToggle: (value){
                part.select=value;
                updateRedPoint();
              }),
          SizedBox(width: ViewUtil.screenWidth(10),),
          Text(part.name),
          Expanded(child: Container()),
          Visibility(

              visible: part.select,
              child: SizedBox(width: 230,
              child: ShadInput(
                textAlign: TextAlign.end,
                initialValue: MathUtil.formatDouble(part.count, 2),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                  XNumberTextInputFormatter(
                      maxIntegerLength: null,
                      maxDecimalLength: 2,
                      isAllowDecimal: true),
                ],
                prefix: const Text('数量'),
                placeholder: const Text('请输入数量'),
                onChanged: (value){
                  part.count=double.parse(value);
                },

              ),
              )),


        ],

      ));

      views.add(ViewUtil.lineView());
    }
    return Column(
      children: views,
    );
  }


  void initSelectData(){

    if(widget.pricePart.config.isNotEmpty){
     var config= jsonDecode(widget.pricePart.config);
     for(var item in config){
       var id=item["id"];
       var count=item["count"];
       hasSelect[id]=count;
     }
    }
  }

  void initTreeDatas(List allParts){
    var trees=treeview.TreeNode.root();
    for(PricePart part in allParts){
      if(selectPricePart.name.isEmpty){
        selectPricePart=part;
      }
      part.path=part.id;
      treeview.TreeNode node= treeview.TreeNode(key: part.id,data:part);
      for(PricePart brand in part.materialList){

        brand.path="${part.id}.${brand.id}";
        treeview.TreeNode brandNode=treeview.TreeNode(key: brand.id,data: brand);

        for(PricePart serial in brand.materialList){

          serial.path="${part.id}.${brand.id}.${serial.id}";
          treeview.TreeNode serialNode=treeview.TreeNode(key: serial.id,data: serial);

          for(PricePart part in serial.materialList){
             if(hasSelect.containsKey(part.id)){
               var count=hasSelect[part.id];
               part.select=true;
               part.count=double.parse(count.toString());
             }else{
               part.select=false;
               part.count=1;
             }
          }
          brandNode.add(serialNode);
        }
        node.add(brandNode);
      }
      trees.add(node);

    }
    sampleTree=trees;
    updateRedPoint();



  }



  void submit(){
    bool isOk=true;
    List selects=[];
    for(var type in allDatas){
      if(!isOk)break;
      for(var brand in type.materialList){
        if(!isOk)break;
        for(var serial in brand.materialList){
          if(!isOk)break;
          for(var part in serial.materialList){
            if(!isOk)break;
            if(part.select){
              if(part.count==0){
                ToastUtil.showToast("${part.name}请输入数量");
                isOk=false;
                break;
              }else{
                selects.add({"id":part.id,"count":part.count});
              }
            }
          }
        }
      }
    }

    if(!isOk)return;
    if(selects.isEmpty){
      ToastUtil.showToast("请选择型号");
    }
    var parm={
      "modelId":widget.pricePart.id,
      "config":selects,
    };
    BaseRequest.postHttp("price/modelconfig",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("编辑成功");
        eventBus.fire(EventRefreshBase());
      }
      Navigator.pop(context);
    }, onError: (error){

    });

  }

}
